package com.capgemini.edealinovaconnection;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.capgemini.edealinovaconnection.dao.DaoMaster;
import com.capgemini.edealinovaconnection.dao.DaoSession;
import com.capgemini.edealinovaconnection.dao.DaoMaster.DevOpenHelper;
import com.capgemini.edealinovaconnection.dao.Idea;
import com.capgemini.edealinovaconnection.dao.IdeaDao;
import com.capgemini.edealinovaconnection.dao.Workshop;
import com.capgemini.edealinovaconnection.dao.WorkshopDao;
import com.capgemini.edealinovaconnection.dummy.EntityElements;


public class DatabaseSynchronisation {

	private Context context;
	private SQLiteDatabase db;
	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private IdeaDao ideaDao;
	private WorkshopDao workshopDao;
	
	public DatabaseSynchronisation(Context context)
	{
		this.context = context;
	}

	public void initDatabase()
	{
		DevOpenHelper helper = new DevOpenHelper(context, "edeal-db", null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        ideaDao = daoSession.getIdeaDao();
        workshopDao = daoSession.getWorkshopDao();
	}
	
	public void insertEntity(String nameEntity, EntityElements entity)
	{
		Date update = Calendar.getInstance().getTime();
		if(nameEntity.equals("Workshop"))
		{	
			Workshop workshop = new Workshop();
			workshop.setIdBase(Integer.valueOf(entity.id));
			workshop.setName(entity.name);
			workshop.setLastChange(update);
			workshopDao.insert(workshop);
			
		}else if (nameEntity.equals("Idea"))
		{
			Idea idea = new Idea();
			idea.setIdBase(Integer.valueOf(entity.id));
			idea.setName(entity.name);
			idea.setLastChange(update);
			ideaDao.insert(idea);
		}else
		{
			//doNothing();
		}
	}
	
	public void removeAllEntites()
	{
		DaoMaster.dropAllTables(db, true);
	}
	
	public long retrieveEntityCount(String nameEntity)
	{
		long count = 0;
		if(nameEntity.equals("Workshop"))
		{
			count = workshopDao.count();
		}else if (nameEntity.equals("Idea"))
		{
			count = ideaDao.count();
		}
		
		return count;
		
	}
	
	public List<Workshop> retrieveWorkshop()
	{
		List<Workshop> workshopArrayList = workshopDao.queryBuilder().list();
		return workshopArrayList;
	}
	
	public List<Idea> retrieveIdea()
	{
		List<Idea> ideaArrayList = ideaDao.queryBuilder().list();
		return ideaArrayList;
	}
}
